﻿using AIStudio.Wpf.Controls.Helper;
using PMIS.Models;
using System.Diagnostics;
using System.Windows;

namespace PMIS.Common.Permission
{
    public class PermissionHelper
    {
        public static readonly DependencyProperty HasPermProperty = DependencyProperty.RegisterAttached(
          "HasPerm", typeof(string), typeof(PermissionHelper), new PropertyMetadata(default(string), OnHasPermPropertyChangedCallback));

        public static void SetHasPerm(DependencyObject element, string value)
        {
            element.SetValue(HasPermProperty, value);
        }

        public static string GetHasPerm(DependencyObject element)
        {
            return (string)element.GetValue(HasPermProperty);
        }

        private static void OnHasPermPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            if (DesignerHelper.IsInDesignMode) return;
            string authorizeCode = dependencyPropertyChangedEventArgs.NewValue as string;

            Debug.Assert(!string.IsNullOrEmpty(authorizeCode), "authorizeCode can't be empty");

            var menu = AccountInfo.Instance.MenuList.Where(x => x.AuthorizeCode == authorizeCode).FirstOrDefault();
            bool hasPermission = false;
            if (menu != null)
            {
                hasPermission = AccountInfo.Instance.MenuIdList.Contains(menu.Id);
            }

            if (dependencyObject is FrameworkElement element)
            {
                if (hasPermission)
                {
                    element.Visibility = Visibility.Visible;
                }
                else
                {
                    element.Visibility = Visibility.Collapsed;
                }
            }
            else if (dependencyObject is Microsoft.Xaml.Behaviors.TriggerAction trigger)
            {
                if (hasPermission)
                {
                    trigger.IsEnabled = true;
                }
                else
                {
                    trigger.IsEnabled = false;
                }
            }
        }
    }
}
